package self.seon.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import self.seon.domain.IpAddress;
import self.seon.domain.LoginRecord;
import self.seon.domain.LoginUser;
import self.seon.domain.User;
import self.seon.domain.http.ResponseResult;
import self.seon.mapper.LoginRecordMapper;
import self.seon.service.DoorService;
import self.seon.utils.IPUtil;
import self.seon.utils.JwtUtil;
import self.seon.utils.RedisCache;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Objects;

/**
 * @author Seon
 * @date 2022/8/30 23:56
 */
@Slf4j
@Service
public class DoorServiceImpl implements DoorService {
    // https://ip.useragentinfo.com/api 查询ip属地的免费的接口
    private final String queryIpUrl = "https://ip.useragentinfo.com/json";
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IPUtil ipUtil;
    @Autowired
    private LoginRecordMapper loginRecordMapper;

    @Override
    public ResponseResult<?> login(HttpServletRequest request, User user) {
        /**
         * 1. 进行对应的认证，没过的话给出对应的提示
         * 2. 认证通过了，就用userid生成一个jwt 同时吧jwt存入ResponseResult中，返回给前端
         * 3. 把完整的信息存入redis，userid作为key，用户信息作为value
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());

        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        User success = loginUser.getUser();
        String token = JwtUtil.createJWT(success.getId().toString(), success.getPassword(), JwtUtil.JWT_TTL);

        // 存入redis
        redisCache.setCacheObject("login:" + success.getId(), loginUser);

        // 获取ip并且根据ip获取属地
        HashMap<String, Object> map = new HashMap<>(2);
        String ip = ipUtil.getIp(request);
        String ipAddress = ipUtil.getIpAddress(queryIpUrl, ip);
        IpAddress parseAddress = JSON.parseObject(ipAddress, IpAddress.class);
        // 不给前端返回位置信息了
        // map.put("ipAddress", parseAddress);
        map.put("token", token);

        // 把登录记录进行存库(归属地)
        String ownerPlace = parseAddress.getCountry() + "-" + parseAddress.getProvince() + "-" +
                parseAddress.getCity() + "-" + parseAddress.getArea() + "-" + parseAddress.getIsp();
        LoginRecord loginRecord = LoginRecord.builder()
                .address(ownerPlace)
                .ip(parseAddress.getIp())
                .build();
        loginRecordMapper.insert(loginRecord);

        log.info("用户登录成功 id = {}", success.getId());
        log.info("{}号用户登录信息为：{}", success.getId(), parseAddress);

        ResponseResult<Object> result = ResponseResult.builder()
                .code(200)
                .msg("登录成功")
                .data(map)
                .build();

        return result;
    }

    @Override
    public ResponseResult<?> logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 获取SecurityContextHolder中的用户id
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long id = loginUser.getUser().getId();
        // 删除redis中的key
        String redisKey = "login:" + id;
        if (redisCache.deleteObject(redisKey)) {
            log.info("用户{},已经下线喽", id);
            return new ResponseResult<>(200, "登出成功", true);
        } else {
            return new ResponseResult<>(400, "登出失败", false);
        }
    }
}
